<template>
  <!-- 服务管理 -->
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        ref="searchForm"
        :model="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 内部显示推荐单位名称 -->
        <Form-item prop="evaluationTargetOrg" :label="'推荐单位名称'" v-if="row.data.permission.isSystemInside">
          <Select v-model="searchForm.evaluationTargetOrg" clearable @on-change="searchValueSet">
            <Option v-for="item in treeData" :value="item.orgCode" :key="item.orgCode">{{ item.orgName }}</Option>
          </Select>
        </Form-item>
        <!-- 外部显示评委单位名称 -->
        <Form-item prop="org" :label="'单位名称'" v-if="!row.data.permission.isSystemInside">
          <Select v-model="searchForm.org" clearable @on-change="searchValueSet">
            <Option v-for="item in treeData" :value="item.orgCode" :key="item.orgCode">{{ item.orgName }}</Option>
          </Select>
        </Form-item>
        <!-- 内部显示被评分类型 -->
        <Form-item prop="evaluationTargetFormSubType" :label="'被评分类型'" v-if="row.data.permission.isSystemInside">
          <Select v-model="searchForm.evaluationTargetFormSubType" clearable @on-change="searchValueSet">
            <Option v-for="item in subTypeList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </Form-item>
        <!-- 内部显示被评分对象 -->
        <Form-item prop="evaluationTargetTitle" :label="'被评分对象'" v-if="row.data.permission.isSystemInside">
          <Input
            type="text"
            v-model="searchForm.evaluationTargetTitle"
            placeholder="请输入"
            @on-enter="searchValueSet"
          ></Input>
        </Form-item>

        <Form-item prop="stage" :label="'评分阶段'">
          <Select v-model="searchForm.stage" clearable @on-change="searchValueSet">
            <Option v-for="item in stageList" :value="item.value" :key="item.value">{{ item.name }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="period" :label="'当前评分周期'">
          <Select v-model="searchForm.period" clearable @on-change="searchValueSet">
            <Option v-for="item in periodList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="status" :label="'状态'">
          <Select v-model="searchForm.status" :clearable="!onlyView" @on-change="searchValueSet">
            <Option v-for="item in reportList" :value="item.key" :key="item.key">{{ item.name }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="isPassed" :label="'是否晋级'" v-if="row.data.permission.formCreator">
          <Select v-model="searchForm.isPassed" clearable @on-change="searchValueSet">
            <Option value="1">是</Option>
            <Option value="0">否</Option>
          </Select>
        </Form-item>
        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="searchValueSet()" />
          <RPButton optType="reset" @click="resetAndSearchValueSet()" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable
      ref="valueSetTable"
      v-if="showTable"
      :config="pageTableConfig"
      row-key="id"
      :load-data="handleLoadData"
    >
      <!-- <RPButton optType="create" type="info" @click="handlePass" text="一键晋级" /> -->
    </InnerPageTable>
  </div>
</template>

<script>
import permission from '@/mixin/permission'
import {
  searchRateStatus,
  searchParentRateStatus,
  STATUS_TYPE_APPROVED,
  STATUS_TYPE_DRAFT,
  STATUS_TYPE_PENDING
} from '@/views/formConst'
import {
  judgesTableColumns,
  ownerTableColumns,
  systemOutsidetableColumns,
  ownerSystemOutsideTableColumns
} from './columns'
import { FORM_TYPE_RATING } from '@/views/formConst'
import dataApi from '@/api/formData'
import formCenterApi from '@/api/formCenter'
import { STATUS_TYPE_PUBLISHED } from '@/views/formConst'
import { mapState } from 'vuex'
import passed from './passed.vue'
import writeForm from '@/views/formCenter/writeForm/rateForm/index.vue'
export default {
  name: 'declarationFormList',
  mixins: [permission],
  props: {
    row: {
      type: Object,
      default: () => {}
    },
    onlyView: {
      type: Boolean,
      default: false
    },
    menu: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showTable: false,
      userCode: sessionStorage.userCode,
      operateForms: [],
      formPermissions: {},
      forms: [],
      formType: '',
      treeData: [],
      subTypeList: [],
      reportList: [],
      periodList: [],
      searchForm: {
        evaluationTargetOrg: '',
        evaluationTargetFormSubType: '',
        org: '',
        stage: '',
        evaluationTargetTitle: '',
        period: '',
        status: '',
        isPassed: ''
      },
      stageList: [
        { name: '第1轮评分', value: 1 },
        { name: '第2轮评分', value: 2 },
        { name: '第3轮评分', value: 3 }
      ],
      formIdList: [],
      pageTableConfig: {
        loadDataFn: this.getServiceList,
        columns: judgesTableColumns.bind(this)(),
        autoFirst: false //默认 就是 false, 要配置在这里
      }
    }
  },
  computed: {
    ...mapState(['orgList'])
  },
  async created() {
    if (this.orgList.length <= 0) {
      await this.$store.dispatch('getOrgList')
    }
    this.dealTreeData(this.orgList)
    if (this.row.data.permission.isSystemInside) {
      // 内部表单评价
      if (this.row.data.permission.submitter) {
        //评委
        this.pageTableConfig.columns = judgesTableColumns.bind(this)()
      } else {
        // 制表人
        this.pageTableConfig.columns = ownerTableColumns.bind(this)()
      }
    } else {
      // 外部系统评价
      if (this.row.data.permission.submitter) {
        //评委
        this.pageTableConfig.columns = systemOutsidetableColumns.bind(this)()
      } else {
        // 制表人
        this.pageTableConfig.columns = ownerSystemOutsideTableColumns.bind(this)()
      }
    }
    this.showTable = true
    // 评委显示子单据，使用子单据状态，否则使用父单据状态
    this.reportList = searchParentRateStatus
    if (this.row.data.permission.submitter) {
      this.reportList = searchRateStatus
    }
    //     评分类表单：
    // 1、操作按钮点击【操作】后的列表页：
    // （1）评委：新增流程中配置的评委用户可以操作，不是评委用户报表【操作】按钮置灰，展示自己需要评分的所有状态下的单据，非自己评分的数据不展示，列表操作为【评分】
    // （2）制表人：展示所有评委所有状态下的单据，列表操作为【晋级】
    // 2、操作按钮点击【查看】后的列表页权限如下：
    // （1）对于制表人，展示所有评委“待评分”“已完成”状态下的单据，默认展示“已完成”的单据，“草稿和待提交”状态单据不展示，列表操作为【查看】
    // （2）对于评委用户，展示自己评分“待评分“已完成”状态下的单据，默认展示“已完成”的单据，“草稿和待提交”状态单据不展示，列表操作为【查看】

    if (this.onlyView) {
      let tempReportList = JSON.parse(JSON.stringify(this.reportList))
      tempReportList.shift()
      this.reportList = tempReportList
      this.searchForm.status = this.reportList[this.reportList.length - 1].key
    }
    this.init()
  },
  methods: {
    dealTreeData(orgData) {
      let data = JSON.parse(JSON.stringify(this.treeToFlat(orgData)))
      data.forEach(node => {
        node.checked = false
        node.title = node.orgName
      })
      data[0].children = []
      this.treeData = data
      this.loading = false
    },
    treeToFlat(tree, parentId = null) {
      let flat = []
      for (let node of tree) {
        let copy = { ...node, parentId }
        flat.push(copy)
        if (node.children && node.children.length > 0) {
          flat = flat.concat(this.treeToFlat(node.children, node.id))
        }
      }
      return flat
    },
    async init() {
      console.log('row', this.row)
      //快速跳转
      try {
        const res = await formCenterApi.menuFindList({ menu: this.row.value, status: STATUS_TYPE_PUBLISHED })
        this.operateForms = res.data.data.filter(item => item.permission.operate)
        this.forms = res.data.data
        this.formPermissions = {}
        this.forms.forEach(element => {
          this.formPermissions[element.id] = element.permission
        })
        this.formIdList = this.forms.map(item => item.id)
        // this.subTypeList = [...new Set(this.forms.filter(item => item.subType !== '').map(item => item.subType))];
        if (this.formIdList.length > 0) {
          this.formType = this.forms[0].type
          await this.getPeriodList(this.formIdList) // 确保 getPeriodList 也是 async 函数
          this.searchValueSet()
        }
      } catch (error) {
        // 处理错误，例如记录日志或显示错误消息
        console.error('Error fetching menu list:', error)
      }

      try {
        const result = await dataApi.getMenuChildTypeList(this.formIdList)
        this.subTypeList = result.data
      } catch (error) {
        // 处理第二个 API 调用的错误
        console.error('Error fetching menu child type list:', error)
      }
    },
    async getPeriodList(formIds) {
      const res = await formCenterApi.formReportHistoryPeriod(formIds)
      this.periodList = Array.from(new Set(res.data))
    },
    handleLoadData(item, callback) {
      const info = JSON.parse(item.ext)
      let param = { condition: {} }
      const conditions = []
      let q = { parentId: item.id }
      Object.keys(q).forEach(key => {
        let value = q[key]
        if ((value && typeof value !== 'object') || Object.is(value, 0)) {
          conditions.push({
            fieldId: key,
            operator: 'is',
            value: value
          })
        }
      })
      param.condition.filterInfo = { conjunction: 'and', conditions }
      param.condition.formType = FORM_TYPE_RATING
      param.condition.formIdList = this.formIdList
      dataApi
        .getDataPage({
          ...param,
          pageNum: 1,
          pageSize: 100
        })
        .then(res => {
          let { pageSize, total, pageNum, records, pages } = res.data.data
          records.forEach(row => {
            row.evaluation_target_record_id = info.evaluation_target_record_id
            row.evaluation_target_title = info.evaluation_target_title
            row.evaluation_target_form_id = info.evaluation_target_form_id
            row.evaluation_target_form_sub_type = info.evaluation_target_form_sub_type
            row.evaluation_target_org = info.evaluation_target_org
            row.formName = row.name
            row.stage = this.getStageShowWord(info.stage)
            row.score = row.score || '--'
            row.is_passed = info.is_passed || '--'
            row.judge = row.creator
            row.isChild = true
          })
          callback(records)
        })
    },
    // 跳转到具体表单
    enterForm(data) {
      new this.$sidelipPage(
        writeForm,
        {
          props: {
            id: data.id
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    //编辑和查看
    editForm(row) {
      new this.$sidelipPage(
        writeForm,
        {
          props: {
            row: {
              id: row.formId,
              recordId: row.id,
              updateTime: row.updateTime
              // evaluationTargetFormId: row.evaluationTargetFormId,
              // evaluationTargetRecordId: row.evaluationTargetRecordId,
              // evaluationTargetTitle: row.evaluationTargetTitle,
              // evaluationTargetOrg: row.evaluationTargetOrg,
              // status: row.status,
              // stage: row.stage,
              // createBy: row.createBy,
            },
            isEdit: row.status > 1 ? false : true,
            isDetail: row.status > 1 ? true : false
          }
        },
        () => {
          this.searchValueSet(true)
        }
      )
    },
    // 详情
    viewForm(row) {
      new this.$sidelipPage(
        writeForm,
        {
          props: {
            row: {
              id: row.formId,
              recordId: row.id,
              updateTime: row.updateTime
              // evaluationTargetTitle: row.evaluationTargetTitle,
              // evaluationTargetOrg: row.evaluationTargetOrg,
              // status: row.status,
              // stage: row.stage
            },
            isDetail: true
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    // 晋级
    pass(row) {
      new this.$pageModal(
        passed,
        {
          props: {
            row: row
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    // 一键晋级
    // handlePass() {},
    getServiceList(tableObj) {
      let { responseProcess, param } = tableObj
      const conditions = []
      console.log(param.ascs, '升序')
      console.log(param.descs, '降序')
      Object.keys(this.searchForm).forEach(key => {
        let value = this.searchForm[key]
        if ((value && typeof value !== 'object') || Object.is(value, 0)) {
          let operator = 'is'
          if (typeof value === 'string' && value.includes(',')) {
            value = value.split(',').map(item => Number(item))
            operator = 'in'
          }
          conditions.push({
            fieldId: key,
            operator,
            value: value
          })
        }
      })
      if (param.ascs && param.ascs.length > 0) {
        param.sortPropName = 'score'
        param.sortOrderBy = 'asc'
      } else if (param.descs && param.descs.length > 0) {
        param.sortPropName = 'score'
        param.sortOrderBy = 'desc'
      }
      if (this.row.data.permission.submitter) {
        param.condition.filterInfo = { conjunction: 'and', conditions }
        param.condition.formType = FORM_TYPE_RATING
        param.condition.formIdList = this.formIdList
        //评委查子单据
        dataApi
          .getDataPage({
            ...param,
            currentPage: param.commonPageDTO.currentPage
          })
          .then(res => {
            let { pageSize, total, pageNum, records, pages } = res.data.data
            records.forEach(row => {
              row.judge = row.creator
              row.contact = row.contact || '--'
              row.phone = row.phone || '--'
              row.email = row.email || '--'
              row.period = row.period || '--'
              row.score = row.score || '--'
              row.phone = row.phone || '--'
              row.stage = this.getStageShowWord(row.stage)
              row.evaluation_target_record_id = row.evaluationTargetRecordId
              row.evaluation_target_title = row.evaluationTargetTitle
              row.evaluation_target_form_id = row.evaluationTargetFormId
              row.evaluation_target_form_sub_type = row.evaluationTargetFormSubType
              row.evaluation_target_org = row.evaluationTargetOrg
            })
            responseProcess({
              pageNum: pageNum,
              pageSize: pageSize,
              pages: pages,
              records: records || [],
              total: total
            })
          })
      } else {
        let statusList = null
        if (typeof param.status === 'string' && param.status.includes(',')) {
          statusList = param.status.split(',').map(item => Number(item))
        } else {
          statusList = param.status ? [param.status] : []
        }
        const p = JSON.parse(JSON.stringify(param))
        p.status = ''
        // 制表人
        dataApi
          .parentPage({
            formIdList: this.formIdList,
            pageSize: param.commonPageDTO.pageSize,
            currentPage: param.commonPageDTO.currentPage,
            ...p,
            statusList
          })
          .then(res => {
            let { pageSize, total, pageNum, records, pages, current } = res.data.data
            records.forEach(row => {
              const info = JSON.parse(row.ext)
              row.judge = info.judge
              row.score = info.score || '--'
              row.stage = this.getStageShowWord(info.stage)
              row.period = info.period
              row.evaluation_target_record_id = info.evaluation_target_record_id
              row.evaluation_target_title = info.evaluation_target_title
              row.evaluation_target_form_id = info.evaluation_target_form_id
              row.evaluation_target_form_sub_type = info.evaluation_target_form_sub_type
              row.evaluation_target_org = info.evaluation_target_org
              row.is_passed = info.is_passed
              row.contact = row.contact || '--'
              row.phone = row.phone || '--'
              row.email = row.email || '--'
              row._loading = false
              row.children = []
            })
            responseProcess({
              pageNum: current,
              pageSize: pageSize,
              pages: pages,
              records: records || [],
              total: total
            })
          })
      }
    },
    getStageShowWord(stage) {
      return `第${stage}轮评分`
    },
    searchValueSet(isCurrent) {
      if (!isCurrent) {
        this.$refs['valueSetTable'].currentPage = 1
      }
      this.$refs['valueSetTable'].load(this.searchForm)
    },
    resetAndSearchValueSet() {
      this.$refs['searchForm'].resetFields()
      this.searchValueSet()
    }
  }
}
</script>
<style>
.ivu-table-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
